from django.db import models
from rest_framework.exceptions import ValidationError
import os
from uuid import uuid4
from users.models import CustomUser


def home_image_rename(instance, filename):
    """
    生成一个唯一的文件名，保留原始文件扩展名。
    """
    ext = filename.split('.')[-1]
    # 生成一个基于UUID的新文件名，并保留文件原始扩展名
    new_filename = f"{uuid4()}.{ext}"
    # 定义文件存储的子路径，这里使用模型的一个属性（如name）来创建子目录
    # 确保instance.name是安全的，没有特殊字符等
    sub_folder = 'home_images'
    # 返回新的文件路径和文件名
    return os.path.join(sub_folder, new_filename)


class Inspiration(models.Model):
    """
    灵感模型，代表一个全局设计方案。
    """
    INSPIRATION_CLASSIFY = [
        (1, '卧室'),
        (2, '客厅'),
        (3, '厨房'),
        (4, '餐厅'),
        (5, '门厅'),
        (6, '书房'),
        (7, '卫浴'),
    ]
    designer = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='inspirations',
                               verbose_name='设计师')
    inspiration_classification = models.IntegerField(choices=INSPIRATION_CLASSIFY, default=1, verbose_name='灵感分类')
    big_name = models.CharField(max_length=100, help_text='大标题')
    small_name = models.CharField(max_length=100, help_text='小标题')
    big_description = models.TextField(help_text='灵感描述1')
    small_description = models.TextField(help_text='灵感描述2')
    # image = models.ImageField(upload_to=home_image_rename, null=True, blank=True, help_text='灵感图片')
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.big_name


class Style(models.Model):
    """
    风格模型，代表一个单品设计。
    """
    STYLE_CLASSIFY = [
        (1, '原木风'),
        (2, '北欧风'),
        (3, '简约风'),
        (4, '新中式'),
        (5, '奢侈风'),
        (6, '侘寂风'),
    ]
    designer = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='styles', verbose_name='设计师')
    style_classification = models.IntegerField(choices=STYLE_CLASSIFY, default=1, verbose_name='风格分类')
    name = models.CharField(max_length=100, help_text='名称')
    material = models.CharField(max_length=100, help_text='材质')
    size = models.CharField(max_length=100, help_text='尺寸/规格')
    color = models.CharField(max_length=100, help_text='颜色')
    design_concept = models.TextField(help_text='设计理念')
    process_overview = models.TextField(help_text='工艺概述')
    # image = models.ImageField(upload_to=home_image_rename, null=True, blank=True, help_text='风格图片')
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

class Image(models.Model):
    """
    图片模型，关联到灵感或风格。
    """
    inspiration = models.ForeignKey(Inspiration, related_name='images', on_delete=models.CASCADE, null=True, blank=True)
    style = models.ForeignKey(Style, related_name='images', on_delete=models.CASCADE, null=True, blank=True)
    image = models.ImageField(upload_to=home_image_rename, help_text='上传图片')
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        if self.inspiration:
            return f"{self.inspiration.big_name} 的图片"
        elif self.style:
            return f"{self.style.name} 的图片"
        return "未关联的图片"
class InspirationComment(models.Model):  # 灵感评论
    inspiration = models.ForeignKey(Inspiration, on_delete=models.CASCADE, related_name='comments',
                                    verbose_name='灵感类作品')
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='用户')
    content = models.TextField(verbose_name='评论内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.user.username} - {self.inspiration.big_name}'

class StyleComment(models.Model):  # 风格评论
    style = models.ForeignKey(Style, on_delete=models.CASCADE, related_name='comments',
                              verbose_name='风格类作品')
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='用户')
    content = models.TextField(verbose_name='评论内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.user.username} - {self.style.name}'



class InspirationFavorite(models.Model):
    """
    全局灵感收藏
    """
    STATUS_FAVORITE = [
        (0, '未收藏'),
        (1, '已收藏'),
    ]
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='inspiration_favorites', verbose_name='收藏者')
    inspiration = models.ForeignKey(Inspiration, on_delete=models.CASCADE, related_name='favorited_by', verbose_name='收藏的灵感')
    inspiration_favorite_status = models.IntegerField(choices=STATUS_FAVORITE, default=0, verbose_name='灵感收藏状态')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '全局灵感收藏'
        verbose_name_plural = verbose_name
        constraints = [
            models.UniqueConstraint(fields=['user', 'inspiration'], name='unique_user_inspiration_favorite')
        ]

    def __str__(self):
        return f"{self.user.username} - {self.inspiration.big_name} - {'已收藏' if self.inspiration_favorite_status == 1 else '未收藏'}"


class StyleFavorite(models.Model):
    """
    单品风格收藏
    """
    STATUS_FAVORITE = [
        (0, '未收藏'),
        (1, '已收藏'),
    ]
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='style_favorites', verbose_name='收藏者')
    style = models.ForeignKey(Style, on_delete=models.CASCADE, related_name='favorited_by', verbose_name='收藏的风格')
    style_favorite_status = models.IntegerField(choices=STATUS_FAVORITE, default=0, verbose_name='单品风格收藏状态')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '单品风格收藏'
        verbose_name_plural = verbose_name
        constraints = [
            models.UniqueConstraint(fields=['user', 'style'], name='unique_user_style_favorite')
        ]

    def __str__(self):
        return f"{self.user.username} - {self.style.name} - {'已收藏' if self.style_favorite_status == 1 else '未收藏'}"


class InspirationVoting(models.Model):
    """
    全局灵感投票
    """
    STATUS_VOTING = [
        (0, '未投票'),
        (1, '已投票'),
    ]
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='inspiration_votings', verbose_name='投票者')
    inspiration = models.ForeignKey(Inspiration, on_delete=models.CASCADE, related_name='voted_by', verbose_name='投票的灵感')
    inspiration_voting_status = models.IntegerField(choices=STATUS_VOTING, default=0, verbose_name='灵感投票状态')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '全局灵感投票'
        verbose_name_plural = verbose_name
        constraints = [
            models.UniqueConstraint(fields=['user', 'inspiration'], name='unique_user_inspiration_vote')
        ]

    def __str__(self):
        return f"{self.user.username} - {self.inspiration.big_name} - {'已投票' if self.inspiration_voting_status == 1 else '未投票'}"


class StyleVoting(models.Model):
    """
    单品投票
    """
    STATUS_VOTING = [
        (0, '未投票'),
        (1, '已投票'),
    ]
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='style_votings', verbose_name='投票者')
    style = models.ForeignKey(Style, on_delete=models.CASCADE, related_name='voted_by', verbose_name='投票的风格')
    style_voting_status = models.IntegerField(choices=STATUS_VOTING, default=0, verbose_name='风格单品投票状态')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '单品投票'
        verbose_name_plural = verbose_name
        constraints = [
            models.UniqueConstraint(fields=['user', 'style'], name='unique_user_style_vote')
        ]

    def __str__(self):
        return f"{self.user.username} - {self.style.name} - {'已投票' if self.style_voting_status == 1 else '未投票'}"
